package com.nineclock.message.service.impl;

import com.nineclock.common.constant.MessageConstant;
import com.nineclock.message.config.JPushManager;
import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {


    @Autowired
    JPushManager pushManager;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {

        wrapper(message);
        
        //保存消息到mongodb数据
        mongoTemplate.save(message);

        //通过极光推送到 系统管理员
        boolean flag = pushManager.sendNotificationByAlias("入职申请", message.getContent(), message.getTargets(), null );

        return flag;
    }

    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {

        Query query = new Query();

        if(messageDTO.getId() != null){
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }

        if(messageDTO.getType() != null){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }

        if(messageDTO.getTargetId() != null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }

        if(messageDTO.getUserId() != null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }
        //升序排序
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));

        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);

        return messageList;
    }

    @Override
    public void updateMessageWithApproved(String msgId) {
        //参数1：query 条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(msgId));
        //参数2： 更新：要更新的数据
        Update update = new Update();
        update.set ("useStatus" , 1);
        update.set("approveStatue", 1);
        //参数3：实体类的类型
        mongoTemplate.updateFirst(query, update, NcMessage.class);
    }


    private void wrapper(NcMessage message) {

        message.setMessageType(MessageConstant.COMPANY_APPLY);
        message.setApproveStatue(0);
        message.setCreateTime(new Date());
        message.setTitle("入职申请");
        message.setUseStatus(MessageConstant.STATE_UNREAD);
    }
}
